package com.cxm.qyyz.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cxm.qyyz.R;

import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CountdownLayout extends LinearLayout {

    private OnCountdownListener listener;
    private CountDownTimer countDownTimer;
    private long sumTimeMs;
    private long newTime;
    private boolean isPause;
    private boolean isShowDay;
    private boolean isShowMs;
    private boolean isShowZeroHour = true;
    private boolean isShowDateFormat;
    private int showMsBit;

    public interface OnCountdownListener {
        void onFinish();

        void onTick(long millisUntilFinished);
    }

    public CountdownLayout(Context context) {
        this(context, null);
    }

    public CountdownLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (attrs != null){
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CountdownLayout);
            isShowDay = ta.getBoolean(R.styleable.CountdownLayout_cly_is_show_day,false);
            isShowMs = ta.getBoolean(R.styleable.CountdownLayout_cly_is_show_ms,false);
            showMsBit = ta.getInt(R.styleable.CountdownLayout_cly_show_ms_bit,3);
            isShowDateFormat = ta.getBoolean(R.styleable.CountdownLayout_cly_is_show_date,true);
            ta.recycle();
        }
        if (showMsBit > 3){
            showMsBit = 3;
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        setTime(0);
    }

    private void startTimerTask(long sumTimeMs) {
        if (countDownTimer != null || sumTimeMs <= 0) return;
        long countDownInterval = 1000;
        if (isShowMs){
            countDownInterval = 10;
        }
        countDownTimer = new CountDownTimer(sumTimeMs, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                newTime = millisUntilFinished;
                if (isShowDateFormat) {
                    setViewTime(millisUntilFinished);
                } else {
                    ((TextView) getChildAt(0)).setText(String.valueOf(millisUntilFinished / 1000));
                }

                if (listener != null) {
                    listener.onTick(millisUntilFinished);
                }
            }

            @Override
            public void onFinish() {
                stop();
                if (listener != null) {
                    listener.onFinish();
                }
            }
        };
        countDownTimer.start();
    }

    /**
     * 数组合并
     */
    private <T> T[] arrayMerge(T[] array1, T[] array2){
        if (array1 == null || array2 == null) return null;
        T[] arrayCopy = (T[]) Array.newInstance(array1[0].getClass(),array1.length + array2.length);
        System.arraycopy(array1,0,arrayCopy,0,array1.length);
        System.arraycopy(array2,0,arrayCopy,array1.length,array2.length);
        return arrayCopy;
    }

    private void setViewTime(long millisUntilFinished) {
        if (millisUntilFinished <= 0) millisUntilFinished = 0;
        String[] times = formatTime(millisUntilFinished / 1000).split(":");
        if (times.length > 0){
            if (times[0].contains("天")) {
//                String[] dayHour = times[0].split("天");
//                times = times[1].split(":");
                String[] timeArray = times;
                for (int i = 0; i < timeArray.length; i++) {
                    View child = getChildAt(i * 2);
                    if (child instanceof TextView) {
                        ((TextView) child).setText(timeArray[i]);
                    }
                }
            }else {
                if (!isShowZeroHour) {
                    if (times[0].startsWith("00")){
                        ArrayList<String> list = new ArrayList<>(Arrays.asList(times));
                        list.remove(0);
                        times = list.toArray(new String[0]);
                    }
                }
                for (int i = 0; i < times.length; i++) {
                    View child = getChildAt(i * 2);
                    if (child instanceof TextView) {
                        ((TextView) child).setText(times[i]);
                    }
                }
            }
            if (isShowMs && getChildCount() > times.length){
                int msIndex = getChildCount() - 1;
                View child = getChildAt(msIndex);
                if (child instanceof TextView) {
                    DecimalFormat decimalformat = new DecimalFormat(showMsBit == 3 ? "000" : showMsBit == 2 ? "00" : "0");
                    String ms = decimalformat.format(millisUntilFinished % 1000);
                    ((TextView) child).setText(ms.substring(0,showMsBit));
                }
            }
        }
    }

    public void setOnCountdownListener(OnCountdownListener listener) {
        this.listener = listener;
    }

    public CountdownLayout setTime(long sumTimeMs) {
        this.sumTimeMs = sumTimeMs;
        if (isShowDateFormat) {
            setViewTime(sumTimeMs);
        } else {
            ((TextView) getChildAt(0)).setText(String.valueOf(sumTimeMs / 1000));
        }
        return this;
    }

    public CountdownLayout setIsShowDay(boolean isShowDay) {
        this.isShowDay = isShowDay;
        return this;
    }

    public CountdownLayout setIsShowZeroHour(boolean isShowZeroHour) {
        this.isShowZeroHour = isShowZeroHour;
        return this;
    }

    public CountdownLayout setIsShowMs(boolean isShowMs) {
        this.isShowMs = isShowMs;
        return this;
    }

    public CountdownLayout setShowDateFormat(boolean showDateFormat) {
        isShowDateFormat = showDateFormat;
        return this;
    }

    public void start() {
        if (sumTimeMs == 0) {
            return;
        }
        if (!isPause) {
            startTimerTask(sumTimeMs);
        }
    }

    public void stop() {
        isPause = false;
        if (isShowDateFormat) {
            setViewTime(0);
        } else {
            ((TextView) getChildAt(0)).setText("0");
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    public void pause() {
        isPause = true;
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }

    public void resume() {
        if (isPause) {
            startTimerTask(newTime);
        }
    }

    /**
     * 时间显示
     *
     * @param sumTime,单位s
     * @return
     */
    @SuppressLint("DefaultLocale")
    public String formatTime(long sumTime) {
        long day = sumTime / (3600 * 24);
        long hour = sumTime % (3600 * 24) / 3600;
        long minute = sumTime % (3600 * 24) % 3600 / 60;
        long second = sumTime % (3600 * 24) % 3600 % 60;

        StringBuilder sb = new StringBuilder();
        if (isShowDay) {
            if (day > 0) {
                sb.append(day).append("天");
            }
        } else {
            if (day > 0) {
                hour += day * 24;
            }
        }
        if (hour < 10) {
            sb.append("0");
        }
        sb.append(String.format("%d:", hour));
        if (minute < 10) {
            sb.append("0");
        }
        sb.append(String.format("%d:", minute));
        if (second < 10) {
            sb.append("0");
        }
        sb.append(second);
        return sb.toString();
    }

}
